const { getToken } = require('../utils/gettoken.js')


const persons = [
    {
        id:1,
        username:'admin',
        password:'123456',
        nickname:'管理员',
    },
    {
        id:2,
        username:'杨璐',
        password:'123123',
        nickname:'北方的狼',
    }
]

// express 默认只解析get的请求体 
// 需要安装body-parser中间件

exports.loginHandler = (req,res) => {
    const {username,password} = req.body
    // console.log(username,password);

    // find() 
    const userinfo = persons.find(item => item.username === username && item.password === password
    )
    // console.log(userinfo)

    if(!userinfo){
        res.send({
            code:0,
            message:'登录失败,用户名或者密码错误'
        })
        return
    }

    // 生成token
    const token = getToken({id:userinfo.id,nickname:userinfo.nickname})

    res.send({
        code:1,
        message:'登录成功',
        token:token,
        id:userinfo.id,
    })

}



exports.rpwdHandler = (req,res) => {
    
    const {id,oldpassword,newpassword} = req.body
    //我要知道你修改谁的密码 
    // 原密码必须正确
    const userinfo = persons.find(item=>item.id === id-0 && item.password === oldpassword)

    if(!userinfo){
        res.send({
            code:0,
            message:'修改失败,原密码错误'
        })
        return
    }
    userinfo.password = newpassword
    res.send({
        code:1,
        message:'修改密码成功'
    })

}